const Router = require('koa-router')
const router = new Router()
const mongo = require('../../schedma/db')

var qiniu = require("qiniu");
//需要填写你的 Access Key 和 Secret Key
qiniu.conf.ACCESS_KEY = 'MH58XmKZBxK3cdt5X0m69RlwXIEODapiiIQoGCDO';
qiniu.conf.SECRET_KEY = 'VbGIUlefleSt2oCxG3jOLXOhrwTUqiC6pEbp9QVL';
var mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY);
var config = new qiniu.conf.Config();
var bucketManager = new qiniu.rs.BucketManager(mac, config);
var publicBucketDomain = 'http://pes61p15q.bkt.clouddn.com';
// 公开空间访问链接
// var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
//要上传的空间
bucket = 'martinbook';
const options = {
  scope: bucket,
  returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
}
//上传到七牛后保存的文件名
// key = 'my-nodejs-logo.png';
//构建上传策略函数
function uptoken(bucket, key) {
  var putPolicy = new qiniu.rs.PutPolicy(options)
  return putPolicy.uploadToken();
}

router.post('/upload', async (ctx) => {
  const key = ctx.request.body.key
  const publicDownloadUrl = publicBucketDomain + '/' + key
  token = uptoken(bucket, key);
  await mongo.UserInfo.updateOne({username: ctx.user.name}, {$set: {url: publicDownloadUrl}})
  ctx.body = {
    token,
    domain: publicDownloadUrl
  }
})

module.exports = router